<template>
  <a-modal
    v-model:visible="visible"
    :title="title"
    :mask-closable="false"
    :esc-to-close="false"
    draggable
    :width="width >= 800 ? '800px' : '100%'"
    @before-ok="save"
    @close="reset"
  >
    <GiForm ref="formRef" v-model="form" :options="options" :columns="columns" />
  </a-modal>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue'
import { Message } from '@arco-design/web-vue'
import { useWindowSize } from '@vueuse/core'
import { useResetReactive } from '@/hooks'
import { addDeviceStore, getDeviceStore, updateDeviceStore } from '@/apis/'
import { type Columns, GiForm, type Options } from '@/components/GiForm'

const emit = defineEmits<{
  (e: 'save-success'): void
}>()

const { width } = useWindowSize()

const dataId = ref('')
const visible = ref(false)
const isUpdate = computed(() => !!dataId.value)
const title = computed(() => (isUpdate.value ? '修改设备信息' : '新增设备'))
const formRef = ref<InstanceType<typeof GiForm>>()

// 表单配置
const options: Options = {
  form: {
    size: 'large',
    layout: 'vertical',
    labelColProps: { span: 24 },
    wrapperColProps: { span: 24 }
  },
  btns: { hide: true },
  grid: {
    gutter: 16,
    cols: 2
  }
}

// 表单数据（严格匹配数据库NOT NULL字段）
const [form, resetForm] = useResetReactive({
  deviceName: '',
  category: 0, // 数据库有DEFAULT 0
  managementId: '',
  modelId: '',
  factoryId: '',
  measureUnit: 0, // 数据库有DEFAULT 0
  count: 0, // 数据库NOT NULL
  status: 0, // 数据库NOT NULL且为tinyint
  location: '',
  source: '',
  buyDate: '',
  manufacturer: '',
  purchaseAmount: 0, // 数据库NOT NULL
  unit: '元', // 数据库NOT NULL且有默认值
  remark: '', // 数据库NOT NULL
  checkoutDate: ''
})

// 字典选项（完全匹配数据库枚举值）
const categoryOptions = [
  { value: 0, label: '传感器' },
  { value: 1, label: '仪器仪表' },
  { value: 2, label: '动态采集系统' },
  { value: 3, label: '信息化设备' },
  { value: 4, label: '耗材' },
  { value: 5, label: '其他设备' }
]

const measureUnitOptions = [
  { value: 0, label: '台' },
  { value: 1, label: '支' },
  { value: 2, label: '个' }
]

const statusOptions = [
  { value: 0, label: '归还' },
  { value: 3, label: '报废' }
]


const destinationOptions = [
  { value: 0, label: '周转库' },
  { value: 1, label: '外借' }
]

// 表单列配置
const columns: Columns = reactive([
  {
    label: '设备名称*',
    field: 'deviceName',
    type: 'input',
    rules: [{ required: true, message: '必填项' }],
    gridItemProps: { span: 1 }
  },
  {
    label: '分类*',
    field: 'category',
    type: 'select',
    options: categoryOptions,
    rules: [{ required: true, message: '必填项' }],
    gridItemProps: { span: 1 }
  },
  {
    label: '管理编号*',
    field: 'managementId',
    type: 'input',
    rules: [
      { max: 100, message: '最长100字符' }
    ],
    gridItemProps: { span: 1 }
  },
  {
    label: '型号*',
    field: 'modelId',
    type: 'input',
    rules: [
      { required: true, message: '必填项' },
      { max: 100, message: '最长100字符' }
    ],
    gridItemProps: { span: 1 }
  },
  {
    label: '出厂编号*',
    field: 'factoryId',
    type: 'input',
    rules: [
      { max: 100, message: '最长100字符' }
    ],
    gridItemProps: { span: 1 }
  },
  {
    label: '计量单位*',
    field: 'measureUnit',
    type: 'select',
    options: measureUnitOptions,
    rules: [{ required: true, message: '必填项' }],
    gridItemProps: { span: 1 }
  },
  {
    label: '数量*',
    field: 'count',
    type: 'input-number',
    min: 0,
    rules: [{ required: true, message: '必填项' }],
    gridItemProps: { span: 1 }
  },
  {
    label: '状态*',
    field: 'status',
    type: 'select',
    options: statusOptions,
    rules: [{ required: true, message: '必填项' }],
    gridItemProps: { span: 1 }
  },
  {
    label: '放置位置*',
    field: 'location',
    type: 'input',
    rules: [
      { required: true, message: '必填项' },
      { max: 255, message: '最长255字符' }
    ],
    gridItemProps: { span: 1 }
  },
  {
    label: '购置来源*',
    field: 'source',
    type: 'input',
    rules: [
      { max: 255, message: '最长255字符' }
    ],
    gridItemProps: { span: 1 }
  },
  {
    label: '购置时间*',
    field: 'buyDate',
    type: 'date-picker',
    gridItemProps: { span: 1 }
  },
  {
    label: '生产厂家*',
    field: 'manufacturer',
    type: 'input',
    rules: [
      { max: 255, message: '最长255字符' }
    ],
    gridItemProps: { span: 1 }
  },
  {
    label: '购置金额*',
    field: 'purchaseAmount',
    type: 'input-number',
    min: 0,
    precision: 2,
    gridItemProps: { span: 1 }
  },
  {
    label: '金额单位*',
    field: 'unit',
    type: 'input',
    disabled: true,
    rules: [
      { required: true, message: '必填项' },
      { max: 255, message: '最长255字符' }
    ],
    gridItemProps: { span: 1 }
  },
  {
    label: '校准有效期*',
    field: 'checkoutDate',
    type: 'date-picker',
    gridItemProps: { span: 1 }
  },
  {
    label: '备注*',
    field: 'remark',
    type: 'textarea',
    rules: [
      { max: 100, message: '最长100字符' }
    ],
    gridItemProps: { span: 2 }
  }
])

// 日期格式化（匹配数据库datetime格式）
const formatDateTime = (date: string | Date) => {
  const d = new Date(date)
  return `${d.getFullYear()}-${(d.getMonth()+1).toString().padStart(2,'0')}-${d.getDate().toString().padStart(2,'0')} ${d.getHours().toString().padStart(2,'0')}:${d.getMinutes().toString().padStart(2,'0')}:${d.getSeconds().toString().padStart(2,'0')}`
}

// 重置表单
const reset = () => {
  formRef.value?.formRef?.resetFields()
  resetForm()
}

// 保存逻辑（严格匹配数据库约束）
const save = async () => {
  try {
    // 1. 表单验证
    const isInvalid = await formRef.value?.formRef?.validate()
    if (isInvalid) return false

    // 2. 准备提交数据
    const submitData = {
      ...form,
      buyDate: formatDateTime(form.buyDate),
      checkoutDate: formatDateTime(form.checkoutDate),
      // 确保必填字段有值（即使前端已校验）
      deviceName: form.deviceName || '',
      managementId: form.managementId || '',
      modelId: form.modelId || '',
      factoryId: form.factoryId || '',
      location: form.location || '',
      source: form.source || '',
      manufacturer: form.manufacturer || '',
      remark: form.remark || '',
      // 处理可能为undefined的数字字段
      count: Number(form.count || 0),
      purchaseAmount: Number(form.purchaseAmount || 0)
    }

    console.log('提交数据:', JSON.stringify(submitData, null, 2))

    // 3. 调用API
    const response = isUpdate.value
      ? await updateDeviceStore(submitData, dataId.value)
      : await addDeviceStore(submitData)

    // 4. 严格检查响应
    if (!response?.success) {
      console.error('后端返回错误:', response)
      Message.error(response?.msg || '操作失败')
      return false
    }

    // 5. 成功处理
    Message.success(isUpdate.value ? '修改成功' : '新增成功')
    emit('save-success')
    return true
  } catch (error: any) {
    console.error('完整错误:', error)
    // 处理网络错误或未捕获的异常
    const msg = error.response?.data?.msg || 
                error.message || 
                '请求失败，请检查控制台'
    Message.error(msg)
    return false
  }
}

// 新增设备
const onAdd = async () => {
  reset()
  dataId.value = ''
  visible.value = true
}

// 修改设备
const onUpdate = async (id: string) => {
  reset()
  dataId.value = id
  try {
    const { data } = await getDeviceStore(id)
    Object.assign(form, {
      ...data,
      // 确保数字字段类型正确
      count: data.count ? Number(data.count) : 0,
      purchaseAmount: data.purchaseAmount ? Number(data.purchaseAmount) : 0
    })
    visible.value = true
  } catch (error) {
    console.error('获取数据失败:', error)
    Message.error('获取设备信息失败')
  }
}

defineExpose({ onAdd, onUpdate })
</script>

<style scoped lang="scss">
/* 样式保持不变 */
:deep(.arco-form-item-label) {
  font-weight: bold;
  margin-bottom: 4px;
}

:deep(.arco-form-item-content) {
  margin-bottom: 12px;
}

:deep(.arco-input-number, .arco-input, .arco-select, .arco-textarea) {
  width: 100%;
}
</style>